package com.laikan.reader.article.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookreader.activity.SendCommentActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.FocusCommentAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.FocusCommentBean;
import com.laikan.reader.core.bean.FocusFavorBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.*;

import static android.view.View.VISIBLE;

/**
 * Created by Administrator on 2016/11/2.
 * 看点评论列表页
 */
public class FocusCommentActivity extends BasicActivity {

    private BaseDataBean<FocusCommentBean> result;
    private ArrayList<FocusCommentBean.DataBean> mCommentDataList = new ArrayList<>();
    private HashSet mCommentIdList = new HashSet();
    private FocusCommentAdapter ArticleCommentAdapter;
    private String shorteId;

    private ListView comment_listview;
    private RelativeLayout back_layout;
    private TextView tv_title;
    private ImageView iv_write_comment, iv_back;
    private View item_foot_view;
    private ProgressBar_Modern mModernLoadProgressBar;
    private TipInfoLayout tipinfo;

    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;
    private int PAGE_LIMIT_SIZE = 10;
    private boolean mIsInitData = false;
    private boolean mIsPullDown = true;// 是否下拉
    private boolean isOnPause = false;
    private boolean mIsClickToSupportSuccess = true;//避免发生多次请求
    private boolean isHideBottom = false;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_comment);
        openEventBus();
        iv_back = (ImageView)findViewById(R.id.iv_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        comment_listview = (ListView)findViewById(R.id.comment_listview);
        iv_write_comment = (ImageView)findViewById(R.id.iv_write_comment);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        tipinfo = (TipInfoLayout)findViewById(R.id.tipinfo);
        item_foot_view = LayoutInflater.from(this).inflate(R.layout.item_comment_foot_view, null); //脚布局
        comment_listview.addFooterView(item_foot_view);
    }

    @Override
    protected void initData() {
        openEventBus();
        item_foot_view.setVisibility(View.GONE);
        shorteId = getIntent().getStringExtra("shorteId");
        tv_title.setText(R.string.activity_title_comment);

        ArticleCommentAdapter = new FocusCommentAdapter(mContext, mCommentDataList);
        comment_listview.setAdapter(ArticleCommentAdapter);
        Drawable drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);
        Drawable drawable_write_comment = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_write_comment), Color.parseColor("#66ccdd")));
        iv_write_comment.setImageDrawable(drawable_write_comment);
    }

    @Override
    protected void onResume() {
        if (!isOnPause || SPUtil.getBoolean("refresh_article_comment", false)) {
            mCurrentPage = 1;
            mIsPullDown = true;
            requestCommentData(true);
            SPUtil.putBoolean("refresh_article_comment", false);
        }
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        isOnPause = true;
    }

    /**
     * 获取评论数据
     */
    private void requestCommentData(final boolean isShowLoadingPage) {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("pageNo", mCurrentPage + "");
        map.put("shorteId", shorteId);
        //        map.put("showType", "time");
        //        map.put("pageSize", PAGE_LIMIT_SIZE + "");
        RequestListener requestListener = new RequestListener() {


            @Override
            public void onPreExecute() {
                if (isShowLoadingPage) {
                    tipinfo.setLoading();
                }
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                tipinfo.setHide();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<FocusCommentBean>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            if (!mIsInitData) {
                                mIsInitData = true;
                            }
                            if (result.getData().getList().size() == 0 && mCurrentPage == 1) {
                                tipinfo.setEmptyData(R.string.comment_no_comments_content, R.drawable.lk_no_comment);
                                comment_listview.setVisibility(View.GONE);
                            }else {
                                comment_listview.setVisibility(VISIBLE);
                                if (mIsPullDown) {
                                    // 下拉刷新
                                    ArticleCommentAdapter.setDatas(updateListData(result.getData().getList()));
                                }else {
                                    // 上拉加载,数据追加
                                    ArticleCommentAdapter.setDatas(loadMoreData(result.getData().getList()));
                                }
                            }
                            mCurrentPage = mCommentDataList.size() / PAGE_LIMIT_SIZE + 1;
                            //评论总数
                            tv_title.setText(DeviceUtil.getHtmlFormatedString(FocusCommentActivity.this, R.string.comment_record_total,
                                Integer.parseInt(result.getData().getCount())));
                            int total = Integer.parseInt(PublicUtil.isNum(result.getData().getCount()));
                            if (mCommentDataList.size() >= total) {
                                mCurrentPage = END_LIST_PAGE;
                            }
                            if(result.getData().getList().size() < PAGE_LIMIT_SIZE && mCurrentPage > 1){
                                item_foot_view.setVisibility(VISIBLE);
                                isHideBottom = true;
                            }
                        }
                    }else {
                        finish();
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if (isShowLoadingPage) {
                    tipinfo.setLoadError(R.string.laikan_network_anomaly);
                }else {
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
            }

            @Override
            public void onFinish() {
                mModernLoadProgressBar.setHide();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_focus_comment_list);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private ArrayList<FocusCommentBean.DataBean> updateListData(List<FocusCommentBean.DataBean> list) {
        ArrayList<FocusCommentBean.DataBean> refreshList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!mCommentIdList.contains(list.get(i).getObjectId())) {
                mCommentIdList.add(list.get(i).getObjectId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(mCommentDataList);
        mCommentDataList.clear();
        mCommentDataList.addAll(refreshList);
        refreshList.clear();
        return mCommentDataList;
    }

    private ArrayList<FocusCommentBean.DataBean> loadMoreData(List<FocusCommentBean.DataBean> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mCommentIdList.contains(list.get(i).getObjectId())) {
                mCommentIdList.add(list.get(i).getObjectId());
                mCommentDataList.add(list.get(i));
//            }
        }
        return mCommentDataList;
    }

    @Override
    protected void setListener() {
        iv_write_comment.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        tipinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestCommentData(true);
            }
        });

        ArticleCommentAdapter.setItemClickListener(new FocusCommentAdapter.ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
            }

            @Override
            public void onReplyClick(View view, int position) {
                                replyComment(position);
            }

            @Override
            public void onClickToSupport(View view, int position) {
                //点赞
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else {
                    if (mIsClickToSupportSuccess) {
                        mIsClickToSupportSuccess = false;
                        articleClickToSupport(FocusCommentDetailActivity.CLICKTOSUPPORT_TYPE, mCommentDataList.get(position).getObjectId(), view);
                    }
                }
            }
        });

        comment_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }

            @Override
            public void onScrollStateChanged(AbsListView absListView, int status) {
                if (status == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        if (END_LIST_PAGE == mCurrentPage) {
                            item_foot_view.setVisibility(VISIBLE);
                            mModernLoadProgressBar.setHide();
                        }else {
                            item_foot_view.setVisibility(View.GONE);
                            mIsPullDown = false;
                            if(!isHideBottom){
                                mModernLoadProgressBar.setShow();
                            }
                            requestCommentData(false);
                        }

                    }
                }
            }
        });
    }

    private void replyComment(int positon) {
        Intent intent = new Intent();
        intent.setClass(mContext, FocusCommentDetailActivity.class);
        intent.putExtra("replyId", mCommentDataList.get(positon).getObjectId());
        intent.putExtra("from", "from_focus");
        startActivity(intent);
    }
    /**
     * 点赞
     *
     * @param type :1:评论2:文章
     */
    public void articleClickToSupport(int type, final String objectId, final View view) {
        HashMap<String, String> map = new HashMap<>();
        map.put("objectId", objectId);
        map.put("type", type + "");
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("BookFocusActivity : Comment : " + httpResponse.responseContent);
                BaseDataBean<FocusFavorBean> focusFavor;
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<FocusFavorBean>>() {
                    }.getType();
                    focusFavor = gson.fromJson(httpResponse.responseContent, type);
                    if (focusFavor != null) {
                        if (Constants.RESULT_OK.equals(focusFavor.getResult())) {
                            mIsClickToSupportSuccess = true;
                            for (int i = 0; i < mCommentDataList.size(); i++) {
                                if (mCommentDataList.get(i).getObjectId().equals(objectId)) {
                                    mCommentDataList.get(i).setReviewPraiseNum(focusFavor.getData().getFavorCount());
                                    mCommentDataList.get(i).setPraise(focusFavor.getData().isWasFavor());
                                }
                            }
                            ArticleCommentAdapter.setDatas(mCommentDataList);
                            scaleAnimation(view);

                        }else {
                            ToastMgr.showShortToast(focusFavor.getError_msg());
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
            }

            @Override
            public void onFinish() {
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_focus_update_praise);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void scaleAnimation(View view) {
        //初始化
        Animation scaleAnimation = new ScaleAnimation(0.1f, 1.0f, 0.1f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //设置动画时间
        scaleAnimation.setDuration(500);
        scaleAnimation.setFillAfter(false);
        view.startAnimation(scaleAnimation);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.iv_write_comment:
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }else {
                    startActivity(new Intent().setAction("from_focus_detail").setClass(mContext, SendCommentActivity.class).putExtra("shorteId", shorteId));
                    //                    if (allow) {
                    //                        startActivity(new Intent().setAction("from_focus_detail").setClass(mContext, SendCommentActivity.class).putExtra("shorteId", shorteId));
                    //                    }else {
                    //                        ToastMgr.showShortToast(allowMsg);
                    //                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        super.parseEvent(event);
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER:
                Map mapEvent = event.getEventMap();
                String totallikecount = (String)mapEvent.get("totallikecount");
                String replyid = (String)mapEvent.get("replyId");
                boolean isFavor = (boolean)mapEvent.get("isFavor");
                for(int i=0; i<mCommentDataList.size(); i++){
                    if(mCommentDataList.get(i).getObjectId().equals(replyid)){
                        mCommentDataList.get(i).setReviewPraiseNum(totallikecount);
                        mCommentDataList.get(i).setPraise(isFavor);
                        ArticleCommentAdapter.setDatas(mCommentDataList);
                    }
                }
                break;
            case LaiKanEvent.EVENT_ID_ARTICLE_SEND_REPLY:
                Map map = event.getEventMap();
                String refreshReplyId = (String)map.get("replyId");
                for(int i=0; i<mCommentDataList.size(); i++){
                    if(mCommentDataList.get(i).getObjectId().equals(refreshReplyId)){
                        int currentReplyNum = Integer.parseInt(mCommentDataList.get(i).getReviewReplyNum()) + 1;
                        mCommentDataList.get(i).setReviewReplyNum(currentReplyNum + "");
                        ArticleCommentAdapter.setDatas(mCommentDataList);
                    }
                }
                break;
            default:
                break;
        }
    }
}
